/**
 * Created by douxin on 24/09/2016.
 */

import 'whatwg-fetch';
const storage = window.localStorage;
import _ from 'lodash';
import apiUrl from './ApiUrl';

const isAuthTokenExist = function() {
    return (storage.getItem('token')) ? true: false;
};

const getHeaderOptions = function() {
    const defaultOptions = {
        credentials: 'same-origin'
    };

    if (isAuthTokenExist()) {
        return _.assign({}, defaultOptions, {
            headers: {
                Authorization: 'Bearer' + ' ' + storage.getItem('token')
            }
        })
    } else {
        return defaultOptions;
    }
};

export function httpRequest(url, options) {
    options = options || {};
    const fetchOptions = _.assign({}, getHeaderOptions(), options);
    return new Promise((resolve, reject) => {
        fetch(url, fetchOptions).then(response => {
            if (response.status === 500) {
                window.location.assign(apiUrl.merchant.login);
            } else {
                return response.json();
            }
        }).then(data => {
            console.log('api request:', data);
            if (data.code === 0 && data['data']) {
                resolve(data['data']);
            } else if (data.code === 40001) {
                // user not login
                window.location.assign(apiUrl.merchant.login);
            } else if (data.code === 40002) {
                window.location.assign('#/merchant/notactive');
            } else {
                reject(new Error(data));
            }
        }).catch(err => {
            console.error('api request:', err);
            reject(err);
        });
    });
}